﻿using rmTest.Common.AttrUtil;
using rmTest.Common.ModelUtil;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace rmTest.Common.ExtensionUtil
{
    /// <summary>
    /// 扩张方法类型
    /// </summary>
    public static class OtherExtensionMethod
    {

        /// <summary>
        /// 获取显示属性值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string GetDisplayValue<T>(this T t) where T : PropertyInfo
        {
            Type type = typeof(T);

            string name = string.Empty;// ((PropertyInfo)t).Name;
            PropertyInfo property = null;
            //判断传进来的属性还是类
            if (type.Name == nameof(PropertyInfo) || type.Name == nameof(FieldInfo))
            {
                property = t as PropertyInfo;
                name = property.Name;
            }
            else
            {
                name = type.Name;
            }
            bool isHaveAttr = false;
            if (type.Name == nameof(PropertyInfo))
                isHaveAttr = property.IsDefined(typeof(DisplayBaseAttribute), true);
            else
                isHaveAttr = type.IsDefined(typeof(DisplayBaseAttribute), true);
            if (isHaveAttr)
            {
                object[] attrs;
                if (type.Name == nameof(PropertyInfo))
                    attrs = property.GetCustomAttributes(typeof(DisplayBaseAttribute), false);
                else
                    attrs = type.GetCustomAttributes(typeof(DisplayBaseAttribute), false);
                DisplayBaseAttribute attr = (DisplayBaseAttribute)attrs.FirstOrDefault();
                if (attr != null)
                {
                    name = attr.Name;
                }
            }
            return name;
        }
    }
}
